package com.hd.trans.network

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.hd.trans.TranslationInterior
import com.hd.trans.share.Md5Util
import com.hd.trans.utils.DeviceUtil
import com.hd.trans.utils.LogUtil
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.util.TreeMap

class RecognitionInterceptor : Interceptor {

    private val mGson: Gson by lazy {
        GsonBuilder().disableHtmlEscaping().create()
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (request.body is FormBody) {
            val body = request.body as FormBody?
            val params = TreeMap<String, Any>()
            body?.let {
                for (i in 0 until it.size) {
                    params[it.name(i)] = it.value(i)
                }
            }

            params.takeIf {
                params.containsKey("none")
            }?.remove("none")


            if (!params.containsKey("timestamp")) {
                params["timestamp"] =
                    PreferenceMgr.getInstance().serverTimeStamp / 1000
            }
            params["deviceid"] = DeviceUtil.getDeviceId()
            params["productinfo"] = TranslationInterior.getProductInfo()

            val paramsKet = params.keys
            val jsonBuild = StringBuilder()
            for (key in paramsKet) {
                jsonBuild.append("&").append(key).append("=").append(params[key])
            }
            jsonBuild.deleteCharAt(0)
            jsonBuild.append("hUuPd20171206LuOnD")
            var datasign = Md5Util.getMD5(jsonBuild.toString())
            params["datasign"] = datasign

            val json = mGson.toJson(params)
            if(TranslationInterior.isDebug()){
                LogUtil.d("okhttp.OkHttpClient", json.toString())
            }

            request = request.newBuilder()
                .post(json.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull()))
                .build()
        }
        return chain.proceed(request)
    }
}